package com.defect.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.defect.exception.CodeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;


@Component
public class ImageCodeFilter extends OncePerRequestFilter{
	@Autowired
	private AuthenticationFailureHandler authenticationFailureHandler;
	
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String uri = request.getRequestURI();
		if(uri.trim().equals("/login")) {
			try {
				validate(request);
				filterChain.doFilter(request, response);
			} catch (CodeException e) {
				authenticationFailureHandler.onAuthenticationFailure(request, response, e);
			}
		}else {
			filterChain.doFilter(request, response);
		}
		
	}
	
	public void validate(HttpServletRequest request) {
		String code = request.getParameter("code");
		if(code == null || code.trim().equals("")) {
			throw new CodeException("没有输入验证码");
		}else {
			Object sessionCode = request.getSession().getAttribute("captcha");
			if(sessionCode == null) {
				throw new CodeException("验证码不存在");
			}else if (!code.trim().equals(sessionCode.toString())) {
				throw new CodeException("验证码不匹配");
			}
		}
	}
}
